const CryptoJS = require('./aes.js')
import {
	generateKey as generateRsaKey,
	encryptedData as encryptedDataRsa,
	decryptedData as decryptedDataRsa
} from './rsa'

//AES密钥
const random = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
export function generateKey(length = 16) {
	let str = ''
	for (let i = 0; i < length; i++) {
		str = str + random.charAt(Math.random() * random.length)
	}
	return str
}

const keyPair = {
	// 解密参数使用的前端私钥（与serverKey互相不可解）
	privateKey: 'MIICWwIBAAKBgFqzR6JkQbgejIaucUzi1lMNkmFsVyibHguT6sKNVZDX8eEaoR40' +
		'M9DboCm3bUoZ/EXcGHlglT7pl+VE3sWQYGIY+cOowz9W2tS6pQItgzVMp9Dx90Pz' +
		'PcCwY/PAAFkXuFHs07cMe2U/e0lFI6hJaoUwHeZNGJoiUYM8cITgFhzJAgMBAAEC' +
		'gYBAecmmixacyDqlU0R/n5E0ISW508ZxuzM0j8YG32nAOYJcvw1h50IeasIEZbxv' +
		'POG0160eO6ZcvrmX5clnMCcTO6lzn4Y68dQfLc8ObfuLd1HR1iOAfLgu8rTj1RDF' +
		'dsOmdVbRmM6sGbsxduFmzcMRd+713Ck/omysfdVxcS0fwQJBAKZpwJXO985Id/y0' +
		'vi4t/x3IIQV+4a3i/jiW56WI5QOf8FR3r1hUIWBBDStttiDJhUBgR+5JWGp1Ek7V' +
		'DLsNPU0CQQCLhyh03VGfN1aC0oDl5Ck4oDPvbiB2O/IVIlC8Y6hZaeuDfli5RfGv' +
		'17mpBqWbdrFR4O40yfXu60iUzD8oiY9tAkEAnH/9xqUytQPAG57a79EACEEKlQGD' +
		'OaWs0QlR5oI8ZdFHEhjQhS/xh3UF7p6p1mHOeAFUBEtj5BIfWpXP+CV2TQJAMDPc' +
		'XStMlHW4tG9myoUdXIu0BYaFPnONOZHmVH8VXPaDv6S5oCAy0+3yHRvHwMKrlb7g' +
		'bGpNRWIRbB53v1hurQJADrWxnDw0Ie5IeXQ6LZIrMc5BO5IRFq1W71kNXYYGXbbl' +
		'Tkx9dh527c5CTCc7/IXdEdqCFB7Ubzh75kdoiWKDSg==',
	// 加密参数使用的后端公钥（与privateKey互相不可解）
	serverKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCt8ETRUpNllEdF8IUVeVMq2NvE' +
		'ky+RQuPPN4y7rfMKPJFYI765yTjQoQ5xXwpjru7x085lTvLmCZAcxa1TAlJU0iQZ' +
		'Yh66RrfH97/9ZF4UIB+AfqlwOExsfM0oucJ65s/poU9C3v/myNb2pi8r1HxzUdzN' +
		'zSnEPx32fFWm0KbAjwIDAQAB'
}

//加密
export function Encrypt(data) {
	const aesKey = generateKey(16) //传给后端的加密原始密钥
	if (!data) return data
	const KEY = CryptoJS.enc.Utf8.parse(aesKey); //前端密钥加密所用
	const encrypts = {}
	let srcs = CryptoJS.enc.Utf8.parse(data);
	let encrypted = CryptoJS.AES.encrypt(srcs, KEY, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	});
	encrypts.encryptKey = encryptedDataRsa(aesKey, keyPair.serverKey)
	encrypts.encryptData = CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
	return encrypts
}

//解密
export function Decrypt(encrypts) {
	if (!encrypts) return encrypts
	if (Object.keys(keyPair).length === 0) {
		const genKeyPair = generateRsaKey()
		keyPair.privateKey = genKeyPair.privateKey
		keyPair.publicKey = genKeyPair.publicKey
	}
	const aesKey = decryptedDataRsa(encrypts.encryptKey, keyPair.privateKey)

	const decrypt = CryptoJS.AES.decrypt(encrypts.encryptData, CryptoJS.enc.Utf8.parse(aesKey), {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	})
	return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}
